package com.sky.wsp.webflux.controller;

import com.sky.wsp.webflux.service.UserService;
import com.sky.wsp.webflux.vo.UserVO;
import org.springframework.http.MediaType;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import reactor.core.publisher.Flux;
import reactor.core.publisher.Mono;

import javax.annotation.Resource;

/**
 * @author wangshaopeng@talkweb.com.cn
 * @desccription 在此输入描述
 * @date 2023/10/24
 */
@RestController
@RequestMapping("/user")
public class UserController {
    @Resource
    private UserService userService;

    @GetMapping("/save")
    public Mono<UserVO> save() {
        long l = System.currentTimeMillis();
        UserVO user = new UserVO();
        Mono<UserVO> userVOMono = Mono.fromSupplier(() -> userService.save(user));
        System.out.println("call save: " + (System.currentTimeMillis() - l));
        return userVOMono;
    }

    /**
     * 异步查询，批量返回
     */
    @GetMapping("/list")
    public Flux<UserVO> findList() {
        long l = System.currentTimeMillis();
        Flux<UserVO> userVOFlux = Flux.range(0, 10).map(id -> userService.findById(id));
        System.out.println("call list: " + (System.currentTimeMillis() - l));
        return userVOFlux;
    }

    /**
     * 异步流式返回，TEXT_EVENT_STREAM_VALUE
     */
    @GetMapping(value = "/list-stream", produces = MediaType.TEXT_EVENT_STREAM_VALUE)
    public Flux<UserVO> findListStream() {
        long l = System.currentTimeMillis();
        Flux<UserVO> userVOFlux = Flux.range(0, 10).map(id -> userService.findById(id));
        System.out.println("call list: " + (System.currentTimeMillis() - l));
        return userVOFlux;
    }

}
